package cn.guet.zjb;

import cn.guet.zjb.handle.WebSocketServerHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.http.*;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;

import java.nio.charset.Charset;

public class Server {
  public static void main(String[] args) {
    NioEventLoopGroup eventExecutors = new NioEventLoopGroup();

    try {
      ChannelFuture channelFuture = new ServerBootstrap()
          .group(eventExecutors)
          .channel(NioServerSocketChannel.class)
          .childHandler(new ChannelInitializer<NioSocketChannel>() {
            @Override
            protected void initChannel(NioSocketChannel nioServerSocketChannel) throws Exception {
              ChannelPipeline pipeline = nioServerSocketChannel.pipeline();
              pipeline.addLast(new LoggingHandler(LogLevel.DEBUG));
              pipeline.addLast(new HttpServerCodec());
              pipeline.addLast(new ChunkedWriteHandler());
              pipeline.addLast(new HttpObjectAggregator(8192));
              pipeline.addLast(new WebSocketServerHandler());
            }
          })
          .bind(8080);
      channelFuture.channel().closeFuture().sync();
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      eventExecutors.shutdownGracefully();
    }


  }
}
